package io.ouka.pub.exception.handler;


import io.ouka.pub.exception.BaseException;
import io.ouka.pub.exceptionenum.ArgumentResponseEnum;
import io.ouka.pub.exceptionenum.CommonResponseEnum;
import io.ouka.pub.exceptionenum.ServletResponseEnum;
import io.ouka.pub.response.ResultMsg;
import io.ouka.pub.response.UnifiedMessageSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * User: Ouka
 * Date: 2020-04-26
 * Time: 23:50
 */
@Slf4j
@Component
@ControllerAdvice
public class UnifiedExceptionHandler {

    /**
     * 生产环境
     */
    private final static String ENV_PROD = "pro";

    final UnifiedMessageSource unifiedMessageSource;

    /**
     * 当前环境
     */

    final String profile;

    public UnifiedExceptionHandler(UnifiedMessageSource unifiedMessageSource,
                                   @Value("${spring.profiles.active}") String profile) {
        this.unifiedMessageSource = unifiedMessageSource;
        this.profile=profile;
    }


    /**
     * 获取国际化消息
     *
     * @param e 异常
     * @return
     */
    public String getMessage(BaseException e) {
        String code = "response." + e.toString();
        String message = unifiedMessageSource.getMessage(code, e.getArgs());

        if (message == null || message.isEmpty()) {
            return e.getMessage();
        }

        return message;
    }

    /**
     * 自定义异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public ResultMsg handleBaseException(BaseException e) {
        log.error(e.getMessage(), e);
        return ResultMsg.wrapperFailResult(e.getIResponseEnum().getCode(), getMessage(e), ResultMsg.ExceptionType.BUS_EXCEPTION);
    }

    /**
     * Controller上一层相关异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = {
            NoHandlerFoundException.class,
            HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            HttpMediaTypeNotAcceptableException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            ServletRequestBindingException.class,
            ConversionNotSupportedException.class,
            MissingServletRequestPartException.class,
            AsyncRequestTimeoutException.class
    })
    @ResponseBody
    public ResultMsg handleServletException(Exception e) {
        log.error(e.getMessage(), e);
        int code = CommonResponseEnum.SERVER_ERROR.getCode();
        try {
            ServletResponseEnum servletExceptionEnum = ServletResponseEnum.valueOf(e.getClass().getSimpleName());
            code = servletExceptionEnum.getCode();
        } catch (IllegalArgumentException e1) {
            log.error("class [{}] not defined in enum {}", e.getClass().getName(), ServletResponseEnum.class.getName());
        }

        if (ENV_PROD.equals(profile)) {
            // 当为生产环境, 不适合把具体的异常信息展示给用户, 比如404.
            code = CommonResponseEnum.SERVER_ERROR.getCode();
            BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR);
            String message = getMessage(baseException);
            return ResultMsg.wrapperFailResult(code, message,ResultMsg.ExceptionType.SYS_EXCEPTION);
        }
        return ResultMsg.wrapperFailResult(code, e.getMessage(),ResultMsg.ExceptionType.SYS_EXCEPTION);
    }


    /**
     * 参数绑定异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public ResultMsg handleBindException(BindException e) {
        log.error("参数绑定校验异常", e);

        return wrapperBindingResult(e.getBindingResult());
    }

    /**
     * 参数校验(Valid)异常，将校验失败的所有异常组合成一条错误信息
     *
     * @param e 异常
     * @return 异常结果
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultMsg handleValidException(MethodArgumentNotValidException e) {
        log.error("参数绑定校验异常", e);

        return wrapperBindingResult(e.getBindingResult());
    }

    /**
     * 包装绑定异常结果
     *
     * @param bindingResult 绑定结果
     * @return 异常结果
     */
    private ResultMsg wrapperBindingResult(BindingResult bindingResult) {
        List<String> list = new ArrayList<>();

        for (ObjectError error : bindingResult.getAllErrors()) {
            list.add(error.getDefaultMessage());
        }
        return ResultMsg.wrapperFailResult(ArgumentResponseEnum.VALID_ERROR.getCode(), list,ResultMsg.ExceptionType.BUS_EXCEPTION);
    }

    /**
     * 未定义异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultMsg handleException(Exception e) {
        log.error(e.getMessage(), e);

        if (ENV_PROD.equals(profile)) {
            // 当为生产环境, 不适合把具体的异常信息展示给用户, 比如数据库异常信息.
            int code = CommonResponseEnum.SERVER_ERROR.getCode();
            BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR);
            String message = getMessage(baseException);
            return ResultMsg.wrapperFailResult(code, message,ResultMsg.ExceptionType.SYS_EXCEPTION);
        }

        return ResultMsg.wrapperFailResult(CommonResponseEnum.SERVER_ERROR.getCode(), e.getMessage(), ResultMsg.ExceptionType.SYS_EXCEPTION);
    }

}
